package com.pojoin.system.controller;

import com.pojoin.common.annotation.Log;
import com.pojoin.common.controller.BaseController;
import com.pojoin.common.domain.Tree;
import com.pojoin.common.service.DictService;
import com.pojoin.common.utils.PageUtils;
import com.pojoin.common.utils.Query;
import com.pojoin.common.utils.R;
import com.pojoin.system.dao.GradeDao;
import com.pojoin.system.dao.UserRoleDao;
import com.pojoin.system.domain.*;
import com.pojoin.system.service.OrderService;
import com.pojoin.system.service.RoleService;
import com.pojoin.system.service.ShopuserService;
import com.pojoin.system.service.UserService;
import com.pojoin.system.vo.UserVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;

@RequestMapping("/sys/mem")
@Controller
public class MemberController extends BaseController {
	private final Logger logger = LoggerFactory.getLogger(this.getClass());
	private String prefix="member/mem"  ;
	@Autowired
	UserService userService;
	@Autowired
	RoleService roleService;
	@Autowired
	DictService dictService;
	@Autowired
	UserRoleDao userRoleMapper;
	@Autowired
	OrderService orderService;
	@GetMapping("")
	String user(Model model) {
		model.addAttribute("user",userRoleMapper.getRoleId(userService.get(getUserId()).getUserId()).getRoleId());
		return prefix + "/user";
	}

	@GetMapping("/list")
	@ResponseBody
	PageUtils list(@RequestParam Map<String, Object> params) {
		// 查询列表数据
		Query query = new Query(params);
		List<UserDO> sysUserList = userService.list(query);
		int total = userService.count(query);
		PageUtils pageUtil = new PageUtils(sysUserList, total);
		return pageUtil;
	}

	@Log("添加用户")
	@GetMapping("/add")
	String add(Model model) {
		//List<RoleDO> roles = roleService.list();
		//model.addAttribute("roles", roles);
		String code="";
		String uuid = UUID.randomUUID().toString();
		DateFormat dateFormat=new SimpleDateFormat("yyyy/MM/dd");
		String format = dateFormat.format(new Date());
		code=format+uuid.split("-")[0].substring(0, 4);
		code=code.replace("/", "");
		model.addAttribute("code",code);
		return prefix + "/add";
	}

	@Log("推荐关系图")
	@GetMapping("/relation")
	String relation(Model model) {
		return prefix + "/tree";
	}

	//@Test
	public void getS(){
		String code="";
		String uuid = UUID.randomUUID().toString();
		DateFormat dateFormat=new SimpleDateFormat("yyyy/MM/dd");
		String format = dateFormat.format(new Date());
		code=format+uuid.split("-")[0].substring(0, 4);
		System.out.println(code.replace("/", ""));
	}
	@Log("拨币")
	@PostMapping("/edit")
    @ResponseBody
	String edit( Integer id) {
		logger.info(getUsername()+":"+getUserId()+"修改订单状态-拨币订单"+id);
        return userService.updateBalance(id);
		/*UserDO userDO = userService.get(id);
		model.addAttribute("user", userDO);
		List<RoleDO> roles = roleService.list(id);
		model.addAttribute("roles", roles);*/
	}

	@Log("撤销订单")
	@PostMapping("/chexiao")
	@ResponseBody
	R chexiao(Integer id) {


		OrderDO orderDO=orderService.get(id);
		if(orderDO.getStatus().equals("0")){
			orderDO.setStatus("2");
			orderDO.setId(id);
			orderService.update(orderDO);
			return R.ok();
		}else{
			return  R.error();
		}

		/*UserDO userDO = userService.get(id);
		model.addAttribute("user", userDO);
		List<RoleDO> roles = roleService.list(id);
		model.addAttribute("roles", roles);*/
	}

	@Log("编辑用户")
	@GetMapping("/edit1/{id}")
	String edit1(@PathVariable Long id, Model model, HttpSession session) {
		UserDO userDO = userService.get(id);
		session.setAttribute("user", userDO);
		/*UserDO userDO = userService.get(id);
		model.addAttribute("user", userDO);
		List<RoleDO> roles = roleService.list(id);
		model.addAttribute("roles", roles);*/
		model.addAttribute("user",userDO);
		model.addAttribute("role", userRoleMapper.getRoleId(userService.get(getUserId()).getUserId()).getRoleId());
		return prefix+"/edit";
	}

	@Autowired
	ShopuserService shopuserService;

	@Log("注册用户")
	@PostMapping("/save")
	//@RequiresPermissions("sys:role:save")
	@ResponseBody
	R save( UserDO user) {
//        ShopuserDO shopuserDO=shopuserService.getByPhone(user.getCode());
//        if(shopuserDO!=null){
//            return R.error("app中编号已经存在！");
//        }
		user.setGmtCreate(new Date());
	    logger.info("===="+getUsername()+":"+getUserId()+"注册新用户"+user.getUsername());
		user.setMoney(0d);
	    try {
            int save = userService.save(user);
            if ( save==1) {
                return R.ok();
            }else if(save==7){
                return R.error("该用户不是报单中心");
            }else if(save==5){
            	return R.error("编号已存在");
			}else if(save==2){
            	return R.error("该报单中心未在app中注册！");
			}

			else if(save==500){
            	return R.error("手机号重复");
			}
            return R.error("报单中心不存在");
        }catch (Exception e){
	        e.printStackTrace();
            return R.error("报单中心余额不足,请充值");
        }
	}
	@Log("修改用户")
	@PostMapping("/save1")
	//@RequiresPermissions("sys:role:save")
	@ResponseBody
	R save1( UserDO user,HttpSession httpSession) {
		user.setGmtModified(new Date());
		try {
			UserDO userDO = getUser();
			UserDO session = (UserDO) httpSession.getAttribute("user");
			int count=userService.updateUserLevel(userDO,user,session);
			if (count==-1){
				return R.error("请选择正确的会员级别");
			}else if (count==1){
				return R.ok();
			}else if (count==2){
				return R.error("积分不够请充值");
			}else {
				return R.error("系统不支持会员降级");
			}
		}catch (Exception e){
			e.printStackTrace();
			return R.error();
		}
	}


	@Log("更新用户")
	@PostMapping("/update")
	@ResponseBody
	R update(UserDO user) {
		if (userService.update(user) > 0) {
			return R.ok();
		}
		return R.error();
	}


	@Log("更新用户")
	@PostMapping("/updatePeronal")
	@ResponseBody
	R updatePeronal(UserDO user) {
		if (userService.updatePersonal(user) > 0) {
			return R.ok();
		}
		return R.error();
	}


	@Log("删除用户")
	@PostMapping("/remove")
	@ResponseBody
	R remove(Long id) {
		if (userService.remove(id) > 0) {
			return R.ok();
		}
		return R.error();
	}

	@Log("批量删除用户")
	@PostMapping("/batchRemove")
	@ResponseBody
	R batchRemove(@RequestParam("ids[]") Long[] userIds) {
		int r = userService.batchremove(userIds);
		if (r > 0) {
			return R.ok();
		}
		return R.error();
	}

	@PostMapping("/exit")
	@ResponseBody
	boolean exit(@RequestParam Map<String, Object> params) {
		// 存在，不通过，false
		return !userService.exit(params);
	}

	@Log("请求更改用户密码")
	@GetMapping("/resetPwd/{id}")
	String resetPwd(@PathVariable("id") Long userId, Model model) {

		UserDO userDO = new UserDO();
		userDO.setUserId(userId);
		model.addAttribute("user", userDO);
		return prefix + "/reset_pwd";
	}

	@Log("提交更改用户密码")
	@PostMapping("/resetPwd")
	@ResponseBody
	R resetPwd(UserVO userVO) {
		try{
			userService.resetPwd(userVO,getUser());
			return R.ok();
		}catch (Exception e){
			return R.error(1,e.getMessage());
		}

	}
	@Log("admin提交更改用户密码")
	@PostMapping("/adminResetPwd")
	@ResponseBody
	R adminResetPwd(UserVO userVO) {
		try{
			userService.adminResetPwd(userVO);
			return R.ok();
		}catch (Exception e){
			return R.error(1,e.getMessage());
		}

	}
	@GetMapping("/tree")
	@ResponseBody
	public Tree<UserDO> tree() {
		UserDO user = getUser();
		Tree<UserDO> tree = new Tree<UserDO>();
		tree = userService.getTree(user);
		//tree.setChildren(tree.getChildren().subList(0,tree.getChildren().size()-1));
		return tree;
	}

	@GetMapping("/treeView")
	String treeView() {
		return  prefix + "/userTree";
	}

	@GetMapping("/personal")
	String personal(Model model) {
		UserDO userDO  = userService.get(getUserId());
		model.addAttribute("user",userDO);
		model.addAttribute("hobbyList",dictService.getHobbyList(userDO));
		model.addAttribute("sexList",dictService.getSexList());
		return prefix + "/personal";
	}
	@ResponseBody
	@PostMapping("/uploadImg")
	R uploadImg(@RequestParam("avatar_file") MultipartFile file, String avatar_data, HttpServletRequest request) {
		if ("test".equals(getUsername())) {
			return R.error(1, "演示系统不允许修改,完整体验请部署程序");
		}
		Map<String, Object> result = new HashMap<>();
		try {
			result = userService.updatePersonalImg(file, avatar_data, getUserId());
		} catch (Exception e) {
			return R.error("更新图像失败！");
		}
		if(result!=null && result.size()>0){
			return R.ok(result);
		}else {
			return R.error("更新图像失败！");
		}
	}

	@Log("全部会员列表")
	@GetMapping("/mem")
	@ResponseBody
	PageUtils memlist(@RequestParam Map<String, Object> params) {
		Query query = new Query(params);
		List<UserDO> list = userService.list(query);
		//model.addAttribute("list",list);
		int total = userService.count(query);
		PageUtils pageUtil = new PageUtils(list, total);
		return pageUtil;
	}

	@Log("全部合伙人列表")
	@GetMapping("/partner")
	@ResponseBody
	PageUtils plist(@RequestParam Map<String, Object> params) {
		Query query = new Query(params);
		List<UserDO> list = userService.partners(query);
		int total = userService.countPartner(query);
		PageUtils pageUtil = new PageUtils(list, total);
		return pageUtil;
	}

	@Log("我的推荐")
	@GetMapping("/getMyUser")
	@ResponseBody
	PageUtils getMyUser(@RequestParam Map<String, Object> params) {
		params.put("parentId", getUserId());
		Query query = new Query(params);
		List<UserDO> list = userService.list(query);
		//model.addAttribute("list",list);
		int total = userService.count(query);
		PageUtils pageUtil = new PageUtils(list, total);
		return pageUtil;
	}
	@Log("获取所有的会员")
	@GetMapping("/getAllVip")
	@ResponseBody
	PageUtils getAllVip(@RequestParam Map<String, Object> params) {
		params.put("level", 0);
		Query query = new Query(params);
		List<UserDO> list = userService.list(query);
		//model.addAttribute("list",list);
		int total = userService.count(query);
		PageUtils pageUtil = new PageUtils(list, total);
		return pageUtil;
	}

	@Log("报单中心列表")
	@GetMapping("/orderlist")
	String orderlist(Model model) {
//		List<RoleDO> roles = roleService.list();
//		model.addAttribute("roles", roles);
		return prefix + "/orderlist";
	}
	@Log("去会员列表页面")
	@GetMapping("/mem1")
	String mem(Model model) {
//		List<RoleDO> roles = roleService.list();
//		model.addAttribute("roles", roles);
		return prefix + "/memlist";
	}

	@Log("去会员列表页面")
	@GetMapping("/partner1")
	String partner(Model model) {
		return prefix + "/partner";
	}

	//@Log("通过code获取名字") 该日志过于频繁，去除
	@PostMapping("/getnameBycode")
	@ResponseBody
	public R getnameBycode(String invitateCode,HttpServletResponse response) {
		response.setCharacterEncoding("UTF-8");
		String msg=userService.getnameBycode(invitateCode);
		if(null==msg){
			return R.error("用户不存才");
		}
		return R.ok(msg);
	}
	@Log("获取级别")
	@GetMapping("/findGradeList")
	public String findGradeList(Model model) {
		List<GradeDO> list=userService.findGradeList();
		model.addAttribute("list",list);
		return "system/setup/add";
	}
    @Log("充值记录")
    @GetMapping("/rechargelist")
    String rechargelist(Model model) {
        return prefix + "/rechargelist";
    }
    @Log("充值记录列表")
    @GetMapping("/getRechargelist")
    @ResponseBody
    PageUtils getRechargelist(@RequestParam Map<String, Object> params) {
        Query query = new Query(params);
        List<OrderDO> list = userService.getOrderList(query);
        //model.addAttribute("list",list);
        int total = userService.getOrderCount(query);
        PageUtils pageUtil = new PageUtils(list, total);
        return pageUtil;
    }

	/**
	 * 修改等级区间
	 */
    @Autowired
	GradeDao gradeDao;
	@ResponseBody
	@RequestMapping("/updateGrade")
	public R updateGradeById(GradeDO gradeDO){
		if(gradeDO.getProportion()>1||gradeDO.getProportion()<=0){
			return R.error("在0与1之间");
		}
		if(gradeDO.getId()==1){
			GradeDO next=gradeDao.get(2);
			if(gradeDO.getNumber()>=next.getNumber()||gradeDO.getProportion()>=next.getProportion()){
				return R.error("非法的设置");
			}else{
				gradeDao.update(gradeDO);
			}
		}else if(gradeDO.getId()==5){
			GradeDO next = gradeDao.get(4);
			if (gradeDO.getNumber() <= next.getNumber() || gradeDO.getProportion() <= next.getProportion()) {
				return R.error("非法的设置");
			}else{
				gradeDao.update(gradeDO);
			}
		} else if (gradeDO.getId() > 12) {
			gradeDO.setNumber(0);
			gradeDao.update(gradeDO);
		}else{
			GradeDO pro=gradeDao.get(gradeDO.getId()-1);
			GradeDO next = gradeDao.get(gradeDO.getId() + 1);
			/*if(gradeDO.getNumber()<=pro.getNumber()||gradeDO.getNumber()>=next.getNumber()||gradeDO.getProportion()<=pro.getProportion()||gradeDO.getProportion()>=next.getProportion()){
				return R.error("非法的设置");
			}else{
				gradeDao.update(gradeDO);
			}*/
			gradeDao.update(gradeDO);
		}


		return R.ok();
	}



}
